<template>
  <div
    v-loading="downloadLoading"
    element-loading-text="文件下载中，请稍等..."
    class="file"
  >
    <div class="radio-group">
      <el-radio-group
        v-model="radioGroupVal"
        @change="radioGroupChange"
      >
        <el-tooltip
          v-for="(item, k) in radioGroupList"
          :key="k"
          :content="item.tooltipContent"
          placement="top"
        >
          <template v-if="item.value === '03'">
            <el-radio-button
              :disabled="!copyData"
              :label="item.value"
            >
              <i class="iconfont" :class="item.icon"></i>
            </el-radio-button>
          </template>
          <template v-else>
            <el-radio-button
              :disabled="['02', '04'].includes(item.value) && multipleSelection.length === 0"
              :label="item.value"
            >
              <i class="iconfont" :class="item.icon"></i>
            </el-radio-button>
          </template>
        </el-tooltip>
      </el-radio-group>
    </div>

    <el-table
      ref="table"
      v-loading="loading"
      :data="tableData"
      :max-height="tableHeight"
      @selection-change="handleSelectionChange"
      @row-dblclick="handleRowDblclick"
    >
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column
        v-for="(item, k) in tableColumn"
        :key="k"
        :prop="item.prop"
        :label="item.label"
        :min-width="item.minWidth"
        :width="item.width"
        :show-overflow-tooltip="true"
        :sortable="item.sortable"
        :default-sort="{prop: 'fileName'}"
        :sort-method="sortDevName"
      >
        <template slot-scope="scope">
          <template v-if="item.prop === 'icon'">
            <el-dropdown
              placement="bottom"
              size="mini"
              trigger="hover"
              @command="handleDropdown($event, scope)"
            >
              <span class="el-dropdown-link">
                <i class="iconfont iconicon_more mr-2"></i>
              </span>
              <el-dropdown-menu slot="dropdown" style="min-width: 70px;">
                <el-dropdown-item
                  v-for="(subItem, s_k) in dropdownList"
                  :key="s_k"
                  :command="subItem.value"
                >
                  {{ subItem.label }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
          <template v-else-if="item.prop === 'checkoutStatus'">{{ scope.row[item.prop] === '0' ? '签出' : '未签出' }}</template>
          <template v-else>{{ scope.row[item.prop] }}</template>
        </template>
      </el-table-column>
    </el-table>
    <!-- 单独拎出来避免放在dropdown-menu里面循环 -->
    <div v-show="false">
      <el-upload
        ref="dropdownUpload"
        :show-file-list="false"
        action="no"
        :http-request="handleCheckInfile"
      >
        <span class="dropdownUploadName">上传</span>
      </el-upload>
    </div>

    <Dialog
      ref="fileDialog"
      title="上传文件"
      top="10vh"
      width="480px"
      :is-footer="false"
      :is-click-modal="false"
      @cancel="fdCancel"
    >
      <template>
        <el-upload
          ref="upload"
          drag
          action="no"
          multiple
          :http-request="uploadSubmit"
          :before-remove="beforeRemove"
          :on-remove="handleRemove"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <div class="btn-wrap">
          <el-button
            :disabled="uploadFileArr.length === 0"
            class="btn btn-outline-primary"
            @click="submitUpload"
          >确 定</el-button></div>
      </template>
    </Dialog>

    <Dialog
      ref="delDialog"
      title="提示"
      width="500px"
      top="30vh"
      :btn-text="{submit: '确 认'}"
      @submitSave="handleDel"
      @cancel="radioGroupVal = ''"
    >
      <span class="del-content">
        <i class="iconfont iconar-alert"></i>
        <span>此操作将删除该数据，是否继续？</span>
      </span>
    </Dialog>

  </div>
</template>
<script>
import Dialog from '@/components/Dialog'
import autoTableHeight from '@/utils/autoTableHeight.js'
import {
  postFileQueryPageList,
  postUpload,
  deleteDels,
  putCheckOutfile,
  putCheckInfile,
  postDown,
  postCopy,
  postFileAdd,
  putCancelCheckOutfile
} from '@/api/frontPage/document/index'
import setActionlog from '@/utils/actionlog.js'
export default {
  name: 'File',
  components: {
    Dialog
  },
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      tableHeight: autoTableHeight(380),
      loading: false,
      downloadLoading: false,
      tableData: [],
      tableColumn: [
        {
          prop: 'icon',
          width: '40'
        },
        {
          prop: 'checkoutStatus',
          label: '标记',
          minWidth: '80'
        },
        {
          prop: 'fileName',
          label: '文件名称',
          minWidth: '270',
          sortable: true
        },
        {
          prop: 'sizeStr',
          label: '文件大小',
          minWidth: '85'
        },
        {
          prop: 'fileType',
          label: '文件格式',
          minWidth: '80'
        },
        {
          prop: 'version',
          label: '版本',
          minWidth: '60'
        },
        {
          prop: 'createBy',
          label: '创建人',
          minWidth: '70'
        },
        {
          prop: 'createTime',
          label: '创建时间',
          minWidth: '162'
        },
        {
          prop: 'checkoutUser',
          label: '签出人',
          minWidth: '70'
        },
        {
          prop: 'checkoutDate',
          label: '签出时间',
          minWidth: '162'
        }
      ],
      multipleSelection: [],
      dropdownData: [],
      deleteDelStatus: '',
      downStatus: '',
      radioGroupVal: '',
      radioGroupList: [
        {
          tooltipContent: '添加',
          value: '01',
          icon: 'iconicon_add'
        },
        {
          tooltipContent: '删除',
          value: '02',
          icon: 'iconicon_trash'
        },
        {
          tooltipContent: '粘贴',
          value: '03',
          icon: 'iconniantie'
        },
        {
          tooltipContent: '下载',
          value: '04',
          icon: 'iconxiazai'
        }
      ],
      dropdownList: [
        {
          value: '01',
          label: '预览'
        },
        {
          value: '02',
          label: '签出'
        },
        {
          value: '03',
          label: '签入'
        },
        {
          value: '04',
          label: '删除'
        },
        {
          value: '05',
          label: '复制'
        },
        {
          value: '06',
          label: '取消签出'
        },
        {
          value: '07',
          label: '下载'
        }
      ],
      copyData: null,
      uploadFileArr: [],
      actionlog: {
        instanceId: '', // 当前操作数据的id
        route: this.$route, // 当前路由信息
        typeObj: { // 埋点类型
          value: '',
          name: '',
          specificTypeName: '' // 具体操作的类型
        },
        fileName: []
      }
    }
  },
  watch: {
    id: {
      handler(newVal, oldVal) {
        this.actionlog.instanceId = newVal
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.getTableList()
    this.copyData = JSON.parse(sessionStorage.getItem('copyData'))
  },
  mounted() {
    window.onresize = () => {
      this.tableHeight = autoTableHeight(380)
    }
  },
  methods: {
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleRemove(file, fileList) {
      const newVal = this.uploadFileArr.filter((item) => {
        return item.uid !== file.uid
      })
      this.uploadFileArr = newVal
    },
    // 确定，绑定上传关系
    submitUpload() {
      const fileName = []
      this.uploadFileArr.forEach(item => {
        fileName.push(item.fileName)
      })
      this.actionlog.fileName = fileName
      this.actionlog.typeObj = {
        value: '09',
        name: '添加附件',
        specificTypeName: '添加附件' // 具体操作的类型
      }
      const params = {
        bomId: this.id,
        objectAttachments: this.uploadFileArr
      }
      postFileAdd(params).then((res) => {
        this.$refs.fileDialog.dialogVisible = false
        this.handelSuccess('上传成功')
        // 埋点
        setActionlog(this.actionlog)
        this.$nextTick(() => {
          this.actionlog.fileName = []
          this.actionlog.typeObj = {}
        })
      })
    },
    uploadSubmit(val) {
      const fd = new FormData()
      const self = this
      fd.append('file', val.file)// 传文件
      fd.append('bomId', self.id)// 传projectId
      postUpload(fd, val).then((res) => {
        this.uploadFileArr.push({ uid: val.file.uid, ...res.result })
        val.onSuccess()
      }).catch(() => {
        val.onError()
      })
    },
    fdCancel() {
      this.radioGroupVal = ''
      this.$refs.upload.clearFiles()
      this.uploadFileArr = []
    },
    getTableList() {
      this.loading = true
      postFileQueryPageList(this.id).then(res => {
        this.loading = false
        const records = res.result.records
        let tableData = []
        if (records !== null && records.length) {
          tableData = records
        }
        this.tableData = tableData
      }).catch(() => {
        this.tableData = []
        this.loading = false
      })
    },
    radioGroupChange(val) {
      switch (val) {
        case '01':
          // 添加 上传附件
          this.$refs.fileDialog.dialogVisible = true
          // 埋点设置值
          this.actionlog.fileName = []
          break
        case '02':
          // 删除
          this.$refs.delDialog.dialogVisible = true
          this.deleteDelStatus = '01'
          break
        case '03':
          // 粘贴
          this.handleCopy()
          break
        case '04':
          // 下载
          this.downStatus = '01'
          this.handleDown()
          break
      }
    },
    handleDel() {
      let ids = []
      if (this.deleteDelStatus === '01') {
        ids = this.multipleSelection.map(item => item.id)
      } else if (this.deleteDelStatus === '02') {
        ids = this.dropdownData.map(item => item.id)
      }
      deleteDels(ids).then(res => {
        this.$refs.delDialog.dialogVisible = false
        this.radioGroupVal = ''
        this.handelSuccess('删除成功')
      })
    },
    handleDown() {
      // // 埋点设置值
      this.actionlog.typeObj = {
        value: '04',
        name: '下载',
        specificTypeName: '下载' // 具体操作的类型
      }
      this.actionlog.fileName = [this.multipleSelection.map(item => item.fileName)]
      let ids = []
      if (this.downStatus === '01') {
        // 埋点设置值
        this.actionlog.fileName = [this.multipleSelection.map(item => item.fileName)]

        ids = this.multipleSelection.map(item => item.id)
        setTimeout(() => {
          this.radioGroupVal = ''
          this.$refs.table.clearSelection()
        }, 250)
      } else if (this.downStatus === '02') {
        // 埋点设置值
        this.actionlog.fileName = [this.dropdownData.map(item => item.fileName)]
        ids = this.dropdownData.map(item => item.id)
      }
      this.downloadLoading = true
      postDown(ids).then(res => {
        this.downloadLoading = false
        this.$message({ message: '文件下载成功！！！', type: 'success' })
        const blob = new Blob([res.data])
        const fileName = res.headers.filename
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL对象
          document.body.removeChild(elink)
        } else { // IE10 + 下载
          navigator.msSaveBlob(blob, fileName)
        }
        // 埋点
        setActionlog(this.actionlog)
        this.$nextTick(() => {
          this.actionlog.fileName = []
          this.actionlog.typeObj = {}
        })
      }).catch(() => {
        this.downloadLoading = false
      })
    },
    handleCopy() {
      const copyData = JSON.parse(sessionStorage.getItem('copyData'))
      const params = {
        fromfileId: copyData.id,
        toObjectInsId: this.id
      }
      setTimeout(() => {
        this.radioGroupVal = ''
      }, 250)
      postCopy(params).then(res => {
        this.handelSuccess('粘贴成功')
      })
    },
    handelSuccess(message = '删除成功') {
      this.$message({
        message: message,
        type: 'success'
      })
      this.getTableList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleDropdown(type, scope) {
      this.dropdownData = [scope.row]
      switch (type) {
        case '01':
          // 预览
          this.handlePreview(scope)
          break
        case '02':
          // 签出
          this.handleCheckOutfile(scope.row)
          break
        case '03':
          // 签入
          this.$refs.dropdownUpload.$children[0].$refs.input.click()
          // // 埋点设置值
          this.actionlog.fileName = [scope.row.fileName]
          this.actionlog.typeObj = {
            value: '07',
            name: '签入',
            specificTypeName: '签入' // 具体操作的类型
          }
          break
        case '04':
          // 删除
          this.deleteDelStatus = '02'
          this.$refs.delDialog.dialogVisible = true
          break
        case '05':
          // 复制
          sessionStorage.setItem('copyData', JSON.stringify(scope.row))
          this.copyData = JSON.parse(sessionStorage.getItem('copyData'))
          this.$message({ message: '复制成功', type: 'success' })
          break
        case '06':
          // 取消签出
          this.handleCancelCheckOutfile(scope.row)
          break
        case '07':
          // 下载
          this.downStatus = '02'
          this.handleDown()
          break
      }
    },
    handleCancelCheckOutfile(row) {
      // // 埋点设置值
      this.actionlog.fileName = [row.fileName]
      this.actionlog.typeObj = {
        value: '08',
        name: '取消签出',
        specificTypeName: '取消签出' // 具体操作的类型
      }
      putCancelCheckOutfile(row.id).then(res => {
        this.handelSuccess('取消签出成功')
        // 埋点
        setActionlog(this.actionlog)
        this.$nextTick(() => {
          this.actionlog.fileName = []
          this.actionlog.typeObj = {}
        })
      })
    },
    handleRowDblclick(val) {
      // val.checkoutStatus 0代表签出/1代表未签出
      // 签出的时候调签入接口/未签出的时候调签出接口
      if (val.checkoutStatus === '1') {
        this.handleCheckOutfile(val)
      } else {
        this.dropdownData = [val]
        this.$refs.dropdownUpload.$children[0].$refs.input.click()
        // // 埋点设置值
        this.actionlog.fileName = [val.fileName]
        this.actionlog.typeObj = {
          value: '07',
          name: '签入',
          specificTypeName: '签入' // 具体操作的类型
        }
      }
    },
    // 签出
    handleCheckOutfile(row) {
      // 埋点设置值
      this.actionlog.fileName = [row.fileName]
      this.actionlog.typeObj = {
        value: '06',
        name: '签出',
        specificTypeName: '签出' // 具体操作的类型
      }

      putCheckOutfile(row.id).then(res => {
        this.handelSuccess('签出成功')
        // 埋点
        setActionlog(this.actionlog)
        this.$nextTick(() => {
          this.actionlog.fileName = []
          this.actionlog.typeObj = {}
        })
      })
    },
    // 签入
    handleCheckInfile(val) {
      const fd = new FormData()
      const self = this
      fd.append('file', val.file)// 传文件
      fd.append('id', self.dropdownData[0].id)// 传projectId
      putCheckInfile(fd, val).then((res) => {
        this.handelSuccess('签入成功')
        // 埋点
        setActionlog(this.actionlog)
        this.$nextTick(() => {
          this.actionlog.fileName = []
          this.actionlog.typeObj = {}
        })
      })
    },
    // 预览
    handlePreview(scope) {
      // 埋点设置值
      this.actionlog.fileName = [scope.row.fileName]
      this.actionlog.typeObj = {
        value: '05',
        name: '预览',
        specificTypeName: '预览' // 具体操作的类型
      }
      // 埋点
      setActionlog(this.actionlog)
      this.$nextTick(() => {
        this.actionlog.fileName = []
        this.actionlog.typeObj = {}
      })

      const fileAddressUrl = process.env.VUE_APP_BASE_API + '/plm-sys' + scope.row.fileUrl
      const { href } = this.$router.resolve({
        path: '/preview',
        query: {
          url: fileAddressUrl,
          fileName: scope.row.fileName
        }
      })
      window.open(href, '_blank')
    },
    // 列表名称字段排序
    sortDevName(str1, str2) {
      let res = 0
      if (!str1['fileName'] || !str2['fileName']) {
        res = str1['fileName'].length - str1['fileName'].length
        return res
      }
      const char1 = str1['fileName'][0]
      const char1Type = this.getChartType(char1)
      const char2 = str2['fileName'][0]
      const char2Type = this.getChartType(char2)
      // 类型相同的逐个比较字符
      if (char1Type[0] === char2Type[0]) {
        if (char1 !== char2) {
          if (char1Type[0] === 'zh') {
            res = char1.localeCompare(char2)
          } else if (char1Type[0] === 'en') {
            res = char1.charCodeAt(0) - char2.charCodeAt(0)
          } else {
            res = char1 - char2
          }
        }
      } else {
      // 类型不同的，直接用返回的数字相减
        res = char1Type[1] - char2Type[1]
      }
      return res
    },
    getChartType(char) {
      // 数字可按照排序的要求进行自定义
      // 数字（0->9）->大写字母（A->Z）->小写字母（a->z）->中文拼音（a->z）
      if (/^[\u4e00-\u9fa5]$/.test(char)) {
        return ['zh', 300]
      }
      if (/^[a-zA-Z]$/.test(char)) {
        return ['en', 200]
      }
      if (/^[0-9]$/.test(char)) {
        return ['number', 100]
      }
      return ['others', 999]
    }
  }

}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
@import "~@/assets/styles/variables";
.file {
  border: 1px solid #EFF2F7;
  .radio-group {
    text-align: right;
    width: 100%;
    height: 65px;
    // border: 1px solid #EFF2F7;
    border-bottom: none;
  }
}
::v-deep .el-loading-text {
  font-size: 13px;
}
::v-deep .el-radio-group {
  padding: 17px 12px 0 0;
  label {
    margin: 0;
  }
  .el-radio-button {
    border: none;
    .el-radio-button__inner {
      .iconfont {
        font-size: 12px;
      }
    }
  }
}

::v-deep .el-upload {
  width: 100%;
  .el-upload-dragger {
    width: 100%;
    height: 215px;
    .el-icon-upload {
      margin-top: 80px;
    }
  }
}
.btn-wrap {
  margin: 11px auto 0;
  text-align: center;
  .btn {
    width: 108px;
  }
}
.del-content {
  .iconar-alert {
    color: #f1b44c;
    font-size: 20px;
    line-height: 20px;
    vertical-align: middle;
    padding-right: 12px;
  }
  span {
    line-height: 20px;
    font-size: 14px;
  }
}
</style>
